package com.ycrlkj.android.modulescore.main.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.ycrlkj.android.modulescore.main.R;
import com.ycrlkj.android.modulescore.main.activity.amap.MapRouteFragment;
import com.ycrlkj.android.modulescore.main.apiservice.FreightOrderApiService;
import com.ycrlkj.android.modulescore.main.databinding.ActivityOnlineFreightOrderDetailBinding;
import com.ycrlkj.android.modulescore.main.entity.FreightOrder;
import com.ycrlkj.android.modulespublic.common.constant.RoutePath;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiExceptionHandler;
import com.ycrlkj.android.modulespublic.common.net.exception.ErrorConsumer;
import com.ycrlkj.android.modulespublic.common.net.transformer.ResponseTransformer;
import com.ycrlkj.android.modulespublic.common.utils.xpopup.XPopupUtil;
import com.ycrlkj.android.modulespublic.common.widget.titlebar.MTitleBar;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
@Route(path = RoutePath.PAGE_ONLINE_FREIGHT_ORDER_DETAIL)
public class OnlineFreightOrderDetailActivity extends AppCompatActivity {

    private ActivityOnlineFreightOrderDetailBinding binding;

    @Inject
    FreightOrderApiService freightOrderApiService;

    @Autowired
    String id;

    @Autowired
    double locationDistance;

    private FreightOrder freightOrder;

    public boolean infoShow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityOnlineFreightOrderDetailBinding.inflate(getLayoutInflater());
        binding.setInfoShow(infoShow);
        binding.setLifecycleOwner(this);

        setContentView(binding.getRoot());

        ARouter.getInstance().inject(this);

        if (id == null && id.length() != 19) {
            XPopupUtil.showAlert(this, "未找到订单信息, 关闭页面", new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    OnlineFreightOrderDetailActivity.this.finish();
                }
            });
        }

        initTitleBar();
        get(id);
        initBtn();
    }


    public void initBtn() {
        binding.btnCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String consignorPhone = freightOrder.getConsignorPhone();
                if (TextUtils.isEmpty(consignorPhone)) {
                    ToastUtils.showLong("货主未留电话");
                } else {
                    XPopupUtil.showModal(OnlineFreightOrderDetailActivity.this, "给货主打电话", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + consignorPhone));
                            startActivity(intent);
                        }
                    });

                }
            }
        });

        binding.btnAccept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                XPopupUtil.showModal(OnlineFreightOrderDetailActivity.this, "确定接受此订单吗?", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {

                        //todo 执行接受订单操作

                        ToastUtils.showLong("接受订单成功");
                    }
                });
            }
        });

    }

    @SuppressLint("CheckResult")
    public void get(String id) {
        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(this);
        XPopupUtil.hideLoadingDelay(loadingPopupView);
        freightOrderApiService.getById(id)
                .compose(ResponseTransformer.obtain())
                .subscribe(freightOrder -> {
                    XPopupUtil.hideLoading(loadingPopupView);
                    freightOrder.setLocationDistance(locationDistance);
                    this.freightOrder = freightOrder;
                    binding.setFreightOrder(freightOrder);
                    loadMapFragment(freightOrder.getStartLat(), freightOrder.getStartLng(), freightOrder.getEndLat(), freightOrder.getEndLng());
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        ApiExceptionHandler.doWith(OnlineFreightOrderDetailActivity.this, e);
                    }
                });

    }

    public void loadMapFragment(Double startLat, Double startLng, Double endLat, Double endLng) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        MapRouteFragment mapRouteFragment = MapRouteFragment.newInstance(startLat, startLng, endLat, endLng);
        transaction.replace(R.id.fragment_container, mapRouteFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    public void initTitleBar() {
        MTitleBar titleBar = binding.mTitleBar;
        titleBar.setBtnEvents(new MTitleBar.BtnEvents() {
            @Override
            public void setBtnLeftOnClickListener() {
                OnlineFreightOrderDetailActivity.this.finish();
            }

            @Override
            public void setBtnRightOnClickListener() {

            }
        });
    }


    //页面内嵌有 fragment, 默认按一次返回是先退出 fragment, 再按一次返回才是退出页面
    //本页要求按一次返回就直接退出页面, 需要重写此方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //拦截系统键盘按下事件, 如果是按下返回按钮
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            finish();

            return true;
        } else {
            //如果按下的不是返回按钮, 则执行按钮默认操作
            return super.onKeyDown(keyCode, event);
        }
    }

    public void handleToggleInfo(View view) {
        infoShow = !infoShow;
        binding.setInfoShow(infoShow);
    }
}